package com.hmdp.utils;

import cn.hutool.core.lang.UUID;

import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock {



    private StringRedisTemplate redisTemplate;
    private String name;
    private static final String KEY_PREFIX = "lock:";
    // 增加一个id前缀,防止多个线程的id冲突
    private static final String ID_PREFIX = UUID.randomUUID().toString(true) + "-";
    //

    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;

    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }


    public SimpleRedisLock(StringRedisTemplate redisTemplate, String name) {
        this.redisTemplate = redisTemplate;
        this.name = name;
    }

    @Override
    public boolean tryLock(long timeoutSec) {
        // 获取锁
        // value的值要加上线程的标识，以便在多线程环境下避免死锁
        String threadId = ID_PREFIX + Thread.currentThread().getId();

        Boolean success = redisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name,
                threadId, timeoutSec, TimeUnit.SECONDS);
        // 直接返回有自动拆箱，会抛出空指针异常，所以要加上判断
        return Boolean.TRUE.equals(success);
    }
    // 基于lua脚本实现的释放锁,一行代码，就没有误删了
    @Override
    public void unlock() {
        // 调用lua脚本,提前把锁的脚本定义好，减少网络IO
        redisTemplate.execute(
                UNLOCK_SCRIPT,
                // 传递的参数
                Collections.singletonList(KEY_PREFIX + name),// 锁的key,keys
                // 当前线程标识
                ID_PREFIX + Thread.currentThread().getId() // args
        );
    }
   /* @Override
    public void unlock() {
        // 1.获取当前线程的标识
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        // 2.获取锁中的标识
        String id = redisTemplate.opsForValue().get(KEY_PREFIX + name);
        // 3.判断是否是同一个线程
        if (threadId.equals(id)) {
            // 4.如果是同一个线程，则释放锁
            redisTemplate.delete(KEY_PREFIX + name);
        }
    }*/
}
